package mess;

import com.sun.xml.internal.bind.v2.model.core.ID;

public class LeeCode_24 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
        System.out.println(swapPairs(head));
        System.out.println(swapPairs(new ListNode(1, new ListNode(2))));
        System.out.println(swapPairs(new ListNode(1, new ListNode(2, new ListNode(3)))));
        System.out.println(swapPairs(new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))))));
    }

    private static ListNode swapPairs2(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode start = head;
        ListNode zero = new ListNode(0);
        zero.next = head;
        head = head.next;
        int count = 0;
        while (start != null && start.next != null) {

            ListNode next = start.next;
            ListNode last = next.next;

            start.next = last;
            next.next = start;

            //交换完毕交接处修改
            if (count != 0)
                zero.next.next = next;
            count++;

            //0指针指向start
            zero.next = start;

            start = last;
        }
        return head;
    }

    private static ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode zero = new ListNode(0);
        zero.next = head;
        ListNode start = head;
        head = head.next;
        int count = 0;
        while (start != null && start.next != null) {
            ListNode next = start.next;
            ListNode last = next.next;

            start.next = last;
            next.next = start;
            if (count != 0)
                zero.next.next = zero.next.next == null ? null : next;
            zero.next = start;

            start = last;
            count++;
        }
        return head;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return this.val + " " + next;
        }
    }
}
